//BranchController.scala
package mycore

import chisel3._
import chisel3.util._

class BranchController extends Module{
	val io = IO(new Bundle{
		val isa = Input(new ISA)
		val imm = Input(new IMM)
		val src1 = Input(UInt(64.W))
		val src2 = Input(UInt(64.W))
		val pc = Input(UInt(64.W))

		val branch = Output(Bool())
		val target = Output(UInt(64.W))
	})

	val beq = io.isa.BEQ && (io.src1 === io.src2)
	val bne = io.isa.BNE && ( io.src1 =/= io.src2 )
  	val bgeu = io.isa.BGEU && ( io.src1 >= io.src2 )
  	val bltu = io.isa.BLTU && ( io.src1 < io.src2 )
  	val bge = io.isa.BGE && ( io.src1.asSInt >= io.src2.asSInt )
  	val blt = io.isa.BLT && ( io.src1.asSInt < io.src2.asSInt )
  	val b = beq | bne | bgeu | bltu | bge | blt

  	val jal = io.isa.JAL
  	val jalr = io.isa.JALR	

  	val b_target = io.pc + io.imm.B
  	val jal_target = io.pc + io.imm.J
  	val jalr_target = io.src1 + io.imm.I
	
	io.branch := b | jal | jalr
	
  	when(jal) {
  		io.target := jal_target
  	}.elsewhen(jalr) {
  		io.target := jalr_target
  	}.otherwise {
  		io.target := b_target
  	}

}